package com.jinly.ryder.log.web;

import com.jinly.ryder.account.web.utils.AuthUtil;
import com.jinly.ryder.common.auth.model.AuthRole;
import com.jinly.ryder.common.auth.model.AuthType;
import com.jinly.ryder.common.utils.FileUtil;
import com.jinly.ryder.manage.service.AppInfoService;
import com.jinly.ryder.manage.service.AppInstanceService;
import com.jinly.ryder.manage.service.model.AppInfo;
import com.jinly.ryder.manage.service.model.AppInstance;
import com.jinly.ryder.manage.service.model.setting.LogSetting;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.ObjectUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class RealTimeLogHandshakeInterceptor implements HandshakeInterceptor {

    @Autowired
    private AppInstanceService appInstanceService;

    @Autowired
    private AppInfoService appInfoService;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler, Map<String, Object> attributes) throws Exception {
        String query = request.getURI().getQuery();
        Map<String, String> paramMap = Arrays.stream(query.split("&")).filter(p -> p.split("=").length == 2).collect(Collectors.toMap(p -> p.split("=")[0].trim(), p -> p.split("=")[1].trim()));
        if (paramMap.containsKey("instanceId")) {
            Integer insId = Integer.parseInt(paramMap.get("instanceId"));
            AppInstance appInstance = appInstanceService.get(insId);
            try {
                AuthUtil.check(AuthType.APP, appInstance.getAppName(), AuthRole.DEVELOPER);
            } catch (Exception e) {
                return false;
            }
            if (appInstance != null) {
                AppInfo appInfo = appInfoService.getAppInfo(appInstance.getAppName());
                LogSetting logSetting = appInfo.getLogSetting();
                if (logSetting != null && !ObjectUtils.isEmpty(logSetting.getRootPath())) {
                    attributes.put("host", appInstance.getHost());
                    attributes.put("logFileName", FileUtil.pathAppend(logSetting.getRootPath(), logSetting.getFileName()));
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        log.info("afterHandshake:{}", request.getURI());
    }
}
